package codegenerator.generator;

import org.slf4j.Logger;

import baytony.util.Util;
import baytony.util.log.Log;
import codegenerator.CodeGeneratorException;
import codegenerator.CommonHelper;
import codegenerator.FileBean;
import codegenerator.TableInfo;
import codegenerator.XmlFileBean;

public class JdbcCtxGenerator extends XmlGenerator {
	
	private static final Logger logger = Log.getLogger();
	private static final String APP_CTX = "jdbc.jtmp";
	private static final String DAO_SETTING = "#DaoSetting#";
	private static final String DAO_INFO = "<bean id=\"#className#Dao\" " +
										   "class=\"#projectName#.dao.#className#Dao\" " +
										   "depends-on=\"HibernateUtil\">\n\t\t" +
										   "<qualifier value=\"#className#Dao\"/>\n" +
										   "</bean>\n";
	
	private static final String CLASS_NAME = "#className#";
	private static final String PROJECT_NAME = "#projectName#";
	private static final String DRIVER = "#driver#";
	private static final String JDBC_URL = "#jdbcUrl#";
	private static final String CONNECT_ACC = "#connectAcc#";
	private static final String CONNECT_PW = "#connectPw#";
	private static final String PACKAGE_VO_SCAN = "#PackageVoScan#";
	
	

	@Override
	public FileBean createInfo(TableInfo...tables) throws CodeGeneratorException {
		if(Util.isEmptyArray(tables)) {
			throw new CodeGeneratorException("*** No tables error ***");
		}
		StringBuffer sb = new StringBuffer();
		for(TableInfo table : tables) {
			String temp = DAO_INFO;
			String tableName = table.getName();
			temp = temp.replaceAll(CLASS_NAME, CommonHelper.table2ClassName(tableName));
			temp = temp.replaceAll(PROJECT_NAME, generatorHelper.getProjectName());
			sb.append(temp);
		}
		String jtmpContent = super.readJtmp(APP_CTX);
		jtmpContent = jtmpContent.replaceAll(DAO_SETTING, sb.toString());
		jtmpContent = jtmpContent.replaceAll(DRIVER, generatorHelper.getDriver());
		jtmpContent = jtmpContent.replaceAll(JDBC_URL, generatorHelper.getJdbcUrl());
		jtmpContent = jtmpContent.replaceAll(CONNECT_ACC, generatorHelper.getConnectAcc());
		jtmpContent = jtmpContent.replaceAll(CONNECT_PW, generatorHelper.getConnectPw());
		jtmpContent = jtmpContent.replaceAll(PACKAGE_VO_SCAN, generatorHelper.getPackageVoScanPath());
		FileBean result = new XmlFileBean();
		result.setFileName("jdbc");		
		result.setContent(jtmpContent);
		result.setPath(generatorHelper.getConfigOutputPath());
		return result;
	}

}
